import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, Request, UsePipes, Put } from "@nestjs/common";
import { PageService } from "./page.service";
import { AuthGuard } from "@nestjs/passport";
import { User } from "src/user/entities/user.entity";
import { Page } from "./entities/page.entity";
import { nanoid } from "nanoid";
import { ZodValidationPipe } from "src/zod-validation/zod-validation.pipe";
import { CreatePageDto, createPageSchema, DeletePageDto, deletePageSchema } from "./dto/page.dto";

@Controller("page")
@UseGuards(AuthGuard("jwt"))
export class PageController {
  constructor(private readonly pageService: PageService) {}

  @Get("graph")
  async graph() {
    const graph = await this.pageService.graph();
    return { data: graph, success: true };
  }

  @Post()
  @UsePipes(new ZodValidationPipe(createPageSchema))
  async create(@Body() body: CreatePageDto, @Request() req) {
    const user = new User();
    user.id = req.user.id;
    const page = new Page(body);
    Reflect.set<Page, "pageId">(page, "pageId", "page" + nanoid(6));

    const newUser = await this.pageService.create({ ...page, user });
    return { data: newUser, success: true };
  }

  @Put()
  async update(@Body() body) {
    const newPage = await this.pageService.update(body);
    return { data: newPage, success: true };
  }

  @Get(":pageId")
  async fetch(@Param() params, @Request() req) {
    const page = await this.pageService.fetch({ pageId: params.pageId, userId: req.user.id });
    return { data: page, success: true };
  }

  @Get()
  async list(@Request() req) {
    const list = await this.pageService.list({ userId: req.user.id });
    return { data: list, success: true };
  }

  @Delete()
  @UsePipes(new ZodValidationPipe(deletePageSchema))
  async delete(@Body() body: DeletePageDto, @Request() req) {
    const newUser = await this.pageService.delete({ pageId: body.pageId, userId: req.user.id });
    return { data: newUser, success: true };
  }
}
